﻿/// ********************************
/// 2010.10.22
/// 监控设备接口流量
/// Author:卢融凯
/// ********************************
using System.Collections.Generic;
using System.Net;
using Lextm.SharpSnmpLib;
using Lextm.SharpSnmpLib.Messaging;
using SManage.LibExtension;
using SManage.Model;
using SManage.Model.Trace;

namespace SManage.Infrastructure
{
    public sealed class InterfaceFlowCalc
    {
        public static IDictionary<Mib2_interfaces_ifEntry, InterfaceFlowDescription> GetDeviceFlow(Device device) {
            if (device == null) {
                return null;
            }
            var dict = new Dictionary<Mib2_interfaces_ifEntry, InterfaceFlowDescription>();
            device.Mib2_interfacesReference.Load();
            device.Mib2_interfaces.Mib2_interfaces_ifEntry.Load();
            var interfacesEntry = device.Mib2_interfaces.Mib2_interfaces_ifEntry;
            foreach (var itfs in interfacesEntry) {
                var flow = GetInterfaceFlow(device, itfs.ifIndex);
                dict.Add(itfs, flow);
            }
            return dict;
        }
        
        private static InterfaceFlowDescription GetInterfaceFlow(Device device,int interfaceId) { 
            string ifInOctets = ".1.3.6.1.2.1.2.2.1.10." + interfaceId;
            string ifOutOctets = ".1.3.6.1.2.1.2.2.1.16." + interfaceId;
            string ifSpeed = "1.3.6.1.2.1.2.2.1.5." + interfaceId;

            IList<Variable> variables = new List<Variable>();
            variables.Add(new Variable(new ObjectIdentifier(ifInOctets)));
            variables.Add(new Variable(new ObjectIdentifier(ifOutOctets)));
            variables.Add(new Variable(new ObjectIdentifier(ifSpeed)));
            var result = Messenger.Get(VersionCode.V2, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 161), new OctetString("public"), variables, 10000);

            var flow = new InterfaceFlowDescription(interfaceId, device) {
                IfInOctets  = result.OidValue(ifInOctets).ToInt32(),
                IfOutOctets = result.OidValue(ifOutOctets).ToInt32(),
                IfSpeed     = result.OidValue(ifSpeed).ToInt32()
            };
            return flow;
        }
    }
}
